package com.sf.fy.uav.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.fy.uav.common.enums.ActivityProductTypeEnum;
import com.sf.fy.uav.common.enums.SettingStatusEnum;
import com.sf.fy.uav.common.request.operate.ActivityAddRequest;
import com.sf.fy.uav.common.request.operate.ActivityEditRequest;
import com.sf.fy.uav.common.request.operate.ActivityRewardRulesRequest;
import com.sf.fy.uav.common.request.operate.SysActivityRequest;
import com.sf.fy.uav.common.request.order.DealRequest;
import com.sf.fy.uav.common.response.operational.ActivityRewardRulesResp;
import com.sf.fy.uav.common.response.operational.SysActivityResponse;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.entity.Activity;
import com.sf.fy.uav.entity.ActivityRewardRules;
import com.sf.fy.uav.mapper.ActivityMapper;
import com.sf.fy.uav.mapper.ActivityRewardRulesMapper;
import com.sf.fy.uav.service.IActivityRewardRulesService;
import com.sf.fy.uav.service.IActivityService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2023-08-16
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    private static final Logger log = LoggerFactory.getLogger(ActivityServiceImpl.class);

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityRewardRulesMapper activityRewardRulesMapper;

    @Autowired
    private IActivityRewardRulesService activityRewardRulesService;

    private static final Integer DEL = 0;

    private final static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addActivity(ActivityAddRequest activityAddRequest) {
        List<ActivityRewardRulesRequest> rulesRequests = activityAddRequest.getRulesRequests();
        Map<String, Long> groupedByCodes = rulesRequests.stream()
                .collect(Collectors.groupingBy(
                        p -> p.getProductType().toString(),
                        Collectors.counting()
                ));
        //判断两个不同的奖励规则是否对应不同的产品
        assert groupedByCodes.values().stream().noneMatch(count -> count > 1) : "存在重复推广活动规则";
//        //判断两个不同的奖励规则是否对应不同的产品
//        if (activityAddRequest.getRulesRequests().size() == 2) {
//            if (rulesRequests.get(0).getProductType().compareTo(rulesRequests.get(1).getProductType()) == 0) {
//                log.info("不同奖励规则需要对应不同产品类型");
//                throw new RuntimeException("不同奖励规则需要对应不同产品类型");
//            }
//        }

//        amountCheck(activityAddRequest.getRewardAmount());
        Date date = new Date();
        Activity activity = BeanUtil.copyProperties(activityAddRequest, Activity.class);
        activity.setUpdateTime(date);
        activity.setCreateTime(date);
        activity.setDeleted(false);
        Date startTime = activityAddRequest.getStartActivityTime();
        Date endTime = activityAddRequest.getEndActivityTime();
        if (date.getTime() > startTime.getTime()) {
            throw new RuntimeException("开始时间不能小于当前时间!");
        }
        if (startTime.getTime() >= endTime.getTime()) {
            throw new RuntimeException("开始时间不能大于等于结束时间!");
        }
        dateSubtract(activityAddRequest.getStartActivityTime(), activityAddRequest.getEndActivityTime());
        if (startTime.getTime() > date.getTime()) {
            //还没开始
            activity.setStatus(SettingStatusEnum.NOT_STARTED.getStatus());
//            //设置到期自动上架
//            delayQueue.pushQueue(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.BANNER_UP_COUNT_DOWN + activity.getId(), startTime.getTime() - date.getTime());
        } else {
            if (date.getTime() < endTime.getTime()) {
                activity.setStatus(SettingStatusEnum.ON_DISPLAY.getStatus());
//                //设置到期自动下架
//                delayQueue.pushQueue(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.BANNER_DOWN_COUNT_DOWN + banner.getId(), endTime.getTime() - date.getTime());
            } else {
                activity.setStatus(SettingStatusEnum.ENDED.getStatus());
            }
        }
        //做新增时这段活动时间范围内有无其他活动的验重判断
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        activityQueryWrapper.ne("status", SettingStatusEnum.OFF.getStatus());
        activityQueryWrapper.eq("deleted", DEL);
        List<Activity> activitieList = activityMapper.selectList(activityQueryWrapper);
        for (Activity activityEntry : activitieList) {
            long startActivityTimeLong = activityEntry.getStartActivityTime().getTime();
            long endActivityTimeLong = activityEntry.getEndActivityTime().getTime();
            if (startTime.getTime() < endActivityTimeLong && endTime.getTime() > startActivityTimeLong) {
                throw new RuntimeException("当前时间段内存在其他活动,请重新设置!");
            }
        }
        if (!this.save(activity)) {
            log.info("保存活动失败");
            throw new RuntimeException("保存活动失败");
        }

        //新增活动规则信息
        List<ActivityRewardRules> activityRewardRules = BeanUtil.copyProperties(rulesRequests, ActivityRewardRules.class);
        LocalDateTime now = LocalDateTime.now();
        for (ActivityRewardRules activityRewardRule : activityRewardRules) {
            //校验奖励金额是否违规
            amountCheck(activityRewardRule.getRewardAmount());
            activityRewardRule.setActivityId(activity.getId());
            activityRewardRule.setUpdateTime(now);
            activityRewardRule.setCreateTime(now);
            activityRewardRule.setDeleted(Boolean.FALSE);
        }
        if (!activityRewardRulesService.saveBatch(activityRewardRules)) {
            log.info("保存奖励规则失败");
            throw new RuntimeException("保存奖励规则失败");
        }
    }

    private void amountCheck(BigDecimal amount) {
        String pattern = "^[0-9]+(.[0-9]{1,2})?$";
        boolean isMatch = amount.toString().matches(pattern);
        if (!isMatch) {
            throw new RuntimeException("仅支持输入数字和小数!");
        }
        if (amount.compareTo(new BigDecimal("0.01")) < 0 || amount.compareTo(BigDecimal.ZERO) == 0 || amount.compareTo(new BigDecimal(20)) > 0) {
            throw new RuntimeException("输入范围:0.01-20");
        }
    }

    private void dateSubtract(Date startDate, Date endDate) {
        DateFormat fat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate date1 = LocalDate.parse(fat.format(startDate), formatter);
        LocalDate date2 = LocalDate.parse(fat.format(endDate), formatter);
        Period period = Period.between(date1, date2);
        int years = period.getYears();
        if (years >= 1) {
            throw new RuntimeException("时间跨度最大一年!");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editActivity(ActivityEditRequest activityEditRequest) {
        List<ActivityRewardRulesRequest> rulesRequests = activityEditRequest.getRulesRequests();

        Map<String, Long> groupedByCodes = rulesRequests.stream()
                .collect(Collectors.groupingBy(
                        p -> p.getProductType().toString(),
                        Collectors.counting()
                ));
        //判断两个不同的奖励规则是否对应不同的产品
        assert groupedByCodes.values().stream().noneMatch(count -> count > 1) : "存在重复推广活动规则";

        //判断两个不同的奖励规则是否对应不同的产品
//        if (activityEditRequest.getRulesRequests().size() == 2) {
//            if (rulesRequests.get(0).getProductType().compareTo(rulesRequests.get(1).getProductType()) == 0) {
//                log.info("不同奖励规则需要对应不同产品类型");
//                throw new RuntimeException("不同奖励规则需要对应不同产品类型");
//            }
//        }

        String id = activityEditRequest.getId();
        if (ObjectUtils.isEmpty(id)) {
            throw new RuntimeException("id不能为空");
        }
        Activity activity = activityMapper.selectById(id);
        Date date = new Date();
        if (Objects.equals(SettingStatusEnum.NOT_STARTED.getStatus(), activity.getStatus())) {

//            amountCheck(activityEditRequest.getRewardAmount());
            if (activityEditRequest.getStartActivityTime() == null) {
                throw new RuntimeException("开始时间不能为空!");
            }
            if (ObjectUtils.isEmpty(activity)) {
                throw new RuntimeException("记录不存在");
            }
            if (ObjectUtils.isEmpty(activity)) {
                throw new RuntimeException("记录不存在");
            }
            if (date.getTime() > activityEditRequest.getStartActivityTime().getTime()) {
                throw new RuntimeException("开始时间不能小于当前时间!");
            }
            if (activityEditRequest.getStartActivityTime().getTime() >= activityEditRequest.getEndActivityTime().getTime()) {
                throw new RuntimeException("开始时间不能大于等于结束时间");
            }
            dateSubtract(activityEditRequest.getStartActivityTime(), activityEditRequest.getEndActivityTime());
        }

        if (Objects.equals(SettingStatusEnum.ON_DISPLAY.getStatus(), activity.getStatus())) {
            if (StringUtils.isNotBlank(activityEditRequest.getActivityName())) {
                throw new RuntimeException("进行中的活动不允许修改活动名称!");
            }
            if (activityEditRequest.getRewardType() != null) {
                throw new RuntimeException("进行中的活动不允许修改奖励类型!");
            }
            if (StringUtils.isNotBlank(activityEditRequest.getRewardRule())) {
                throw new RuntimeException("进行中的活动不允许修改奖励规则!");
            }
            if (activityEditRequest.getRewardAmount() != null) {
                throw new RuntimeException("进行中的活动不允许修改奖励金额!");
            }
            if (activityEditRequest.getStartActivityTime() != null) {
                throw new RuntimeException("进行中的活动不允许修改活动开始时间!");
            }
            if (activity.getStartActivityTime().getTime() >= activityEditRequest.getEndActivityTime().getTime()) {
                throw new RuntimeException("结束时间不能小于开始时间");
            }
            dateSubtract(activity.getStartActivityTime(), activityEditRequest.getEndActivityTime());
        }

        List<Activity> activitieEndAndOffList = activityMapper.selectList(new QueryWrapper<Activity>().and(wrapper -> wrapper.eq("status", SettingStatusEnum.ENDED.getStatus())).or(wrapper -> wrapper.eq("status", SettingStatusEnum.OFF.getStatus())).and(wrapper -> wrapper.eq("deleted", DEL)));
        List<String> endAndOffIds = activitieEndAndOffList.stream().map(Activity::getId).toList();
        if (endAndOffIds.contains(id)) {
            throw new RuntimeException("已结束或已下架的活动禁止修改!");
        }
        String activityName = activityEditRequest.getActivityName();
        Date endActivityTime = activityEditRequest.getEndActivityTime();
        Date startActivityTime = activityEditRequest.getStartActivityTime();
        String processedBy = activityEditRequest.getProcessedBy();
        Integer rewardType = activityEditRequest.getRewardType();
        BigDecimal rewardAmount = activityEditRequest.getRewardAmount();
        String rewardRule = activityEditRequest.getRewardRule();
        if (!ObjectUtils.isEmpty(activityName)) {
            activity.setActivityName(activityName);
        }
        if (!ObjectUtils.isEmpty(startActivityTime)) {
            activity.setStartActivityTime(startActivityTime);
        }
        if (!ObjectUtils.isEmpty(endActivityTime)) {
            activity.setEndActivityTime(endActivityTime);
        }
        if (!ObjectUtils.isEmpty(processedBy)) {
            activity.setProcessedBy(processedBy);
        }
        if (!ObjectUtils.isEmpty(rewardType)) {
            activity.setRewardType(rewardType);
        }
        startActivityTime = activity.getStartActivityTime();
        endActivityTime = activity.getEndActivityTime();
        if (startActivityTime.getTime() > date.getTime()) {
            //还没开始
            activity.setStatus(SettingStatusEnum.NOT_STARTED.getStatus());
//            //设置自动上架
//            delayQueue.pushQueue(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.BANNER_UP_COUNT_DOWN + banner.getId(), startTime.getTime() - date.getTime());
        } else {
            if (date.getTime() < endActivityTime.getTime()) {
                activity.setStatus(SettingStatusEnum.ON_DISPLAY.getStatus());
//                //设置自动下架
//                delayQueue.pushQueue(ServicePrefixEnum.EXPRESS_SYSTEM + RedisPrefixKey.BANNER_DOWN_COUNT_DOWN + banner.getId(), endTime.getTime() - date.getTime());
            } else {
                activity.setStatus(SettingStatusEnum.ENDED.getStatus());
            }
        }
        //做编辑时这段活动时间范围内有无其他活动的验重判断
        List<Activity> activitieList = activityMapper.selectList(
                new QueryWrapper<Activity>()
                        .and(wrapper -> wrapper.eq("deleted", DEL))
                        .and(wrapper -> wrapper.eq("status", SettingStatusEnum.NOT_STARTED.getStatus())).
                        or(wrapper -> wrapper.eq("status", SettingStatusEnum.ON_DISPLAY.getStatus()))
        );
        for (Activity activityEntry : activitieList) {
            if (id.equals(activityEntry.getId())) {
                continue;
            }
            long startActivityTimeLong = activityEntry.getStartActivityTime().getTime();
            long endActivityTimeLong = activityEntry.getEndActivityTime().getTime();
            if (startActivityTime.getTime() < endActivityTimeLong && endActivityTime.getTime() > startActivityTimeLong) {
                throw new RuntimeException("当前时间段内存在其他活动,请重新设置!");
            }
        }
        activity.setUpdateTime(date);
        activityMapper.updateById(activity);

        //添加新的奖励规则
        List<ActivityRewardRules> activityRewardRules = BeanUtil.copyProperties(rulesRequests, ActivityRewardRules.class);

        for (ActivityRewardRules rules : activityRewardRules) {
            ActivityRewardRules oldRule = activityRewardRulesService.getOne(new LambdaQueryWrapper<ActivityRewardRules>()
                    .eq(ActivityRewardRules::getActivityId, activity.getId())
                    .eq(ActivityRewardRules::getProductType, rules.getProductType()));
            if (ObjectUtil.isNotNull(oldRule)) {
                rules.setId(oldRule.getId());
            }
        }
        LocalDateTime now = LocalDateTime.now();
        for (ActivityRewardRules activityRewardRule : activityRewardRules) {
            //校验奖励金额是否违规
            amountCheck(activityRewardRule.getRewardAmount());
            activityRewardRule.setActivityId(activity.getId());
            activityRewardRule.setUpdateTime(now);
            if (activityRewardRule.getId() == null) {
                activityRewardRule.setCreateTime(now);
            }
            activityRewardRule.setDeleted(Boolean.FALSE);
        }
        if (!activityRewardRules.isEmpty()) {
            //当编辑传入的规则只有一个的时，需要删除没有传入的规则
//            ActivityRewardRules delRules = activityRewardRulesService.getOne(new LambdaQueryWrapper<ActivityRewardRules>()
//                    .eq(ActivityRewardRules::getActivityId, activity.getId())
//                    .ne(ActivityRewardRules::getProductType, activityRewardRules.get(0).getProductType()));
//            if (ObjectUtil.isNotNull(delRules)) {
//                delRules.setDeleted(true);
//                activityRewardRulesService.updateById(delRules);
//            }
            List<Byte> productTypes = activityRewardRules.stream().map(ActivityRewardRules::getProductType).toList();
            activityRewardRulesService.update(new LambdaUpdateWrapper<ActivityRewardRules>()
                    .in(ActivityRewardRules::getActivityId, activity.getId())
                    .notIn(ActivityRewardRules::getProductType, productTypes)
                    .set(ActivityRewardRules::getDeleted, 1));
        }
        if (!activityRewardRulesService.saveOrUpdateBatch(activityRewardRules)) {
            log.info("更新奖励规则失败");
            throw new RuntimeException("更新奖励规则失败");
        }
    }

    private Boolean checkIsRight(Date endActivityTime, Date startActivityTime, Integer rewardType) {
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
//        activityQueryWrapper.eq();
//        if () {
//
//        }
        return null;
    }

    private QueryWrapper getQueryWrapper(String name, Integer status) {
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(name)) {
            activityQueryWrapper.like("activity_name", name);
        }
        if (!ObjectUtils.isEmpty(status)) {
            activityQueryWrapper.eq("status", status);
        }
        activityQueryWrapper.eq("deleted", false);
        return activityQueryWrapper;
    }

    @Override
    public Long getTotal(String name, Integer status) {
        QueryWrapper<Activity> activityQueryWrapper = this.getQueryWrapper(name, status);
        return activityMapper.selectCount(activityQueryWrapper);
    }

    @Override
    public List<SysActivityResponse> getActivity(SysActivityRequest sysActivityRequest) {
        String name = sysActivityRequest.getActivityName();
        Integer status = sysActivityRequest.getStatus();
        QueryWrapper<Activity> activityQueryWrapper = this.getQueryWrapper(name, status);
        activityQueryWrapper.orderByDesc("create_time");
        Page<Activity> activityPage = new Page<>(sysActivityRequest.getPage(), sysActivityRequest.getSize());
        IPage<Activity> activityIPage = activityMapper.selectPage(activityPage, activityQueryWrapper);
        List<SysActivityResponse> sysActivityResponses = BeanUtil.copyProperties(activityIPage.getRecords(), SysActivityResponse.class);
        if (CollUtil.isEmpty(sysActivityResponses)) {
            return null;
        }
        List<String> activityIds = sysActivityResponses.stream().map(SysActivityResponse::getId).toList();
        List<ActivityRewardRulesResp> activityRewardRulesResps = activityRewardRulesMapper.findListByAcIds(activityIds);
        for (SysActivityResponse sysActivityRespons : sysActivityResponses) {
            StringBuilder sb = new StringBuilder();
            List<ActivityRewardRulesResp> rules = activityRewardRulesResps.stream().filter(item -> item.getActivityId().equals(sysActivityRespons.getId())).toList();
            for (ActivityRewardRulesResp rule : rules) {
                sb.append(rule.getProductTypeName()).append(": 邀请").append(rule.getRewardRule()).append("下单,每单奖励").append(rule.getRewardAmount().setScale(2, RoundingMode.UP).toString()).append("元;\n");
            }
            if (!sb.isEmpty()) {
                //设置奖励规则字段
                sysActivityRespons.setRewardRule(sb.toString());
                sysActivityRespons.setRewardRules(rules);
            }
        }
/*        List<ActivityRewardRules> rulesList = activityRewardRulesService.list(new LambdaQueryWrapper<ActivityRewardRules>()
                .in(ActivityRewardRules::getActivityId, activityIds)
                .eq(ActivityRewardRules::getDeleted, DEL)
                .orderByAsc(ActivityRewardRules::getCreateTime));
        for (SysActivityResponse sysActivityRespons : sysActivityResponses) {
            StringBuilder sb = new StringBuilder();
            List<ActivityRewardRules> rules = rulesList.stream().filter(item -> item.getActivityId().equals(sysActivityRespons.getId())).toList();
            for (ActivityRewardRules rule : rules) {
                if (rule.getProductType().equals(ActivityProductTypeEnum.LOCAL.getCode())) {
                    //同城及时达
                    sb.append(ActivityProductTypeEnum.LOCAL.getName() + ": 邀请" + rule.getRewardRule() + "下单,每单奖励" + rule.getRewardAmount().setScale(2, RoundingMode.UP).toString() + "元;\n");
                } else if (rule.getProductType().equals(ActivityProductTypeEnum.CROSS_REGION.getCode())) {
                    //跨城飞送
                    sb.append(ActivityProductTypeEnum.CROSS_REGION.getName() + ": 邀请" + rule.getRewardRule() + "下单,每单奖励" + rule.getRewardAmount().setScale(2, RoundingMode.UP).toString() + "元;\n");
                }
            }
            if (!sb.isEmpty()) {
                //设置奖励规则字段
                sysActivityRespons.setRewardRule(sb.toString());
                List<ActivityRewardRulesResp> activityRewardRulesResps = BeanUtil.copyProperties(rules, ActivityRewardRulesResp.class);
                sysActivityRespons.setRewardRules(activityRewardRulesResps);
            }*/

        return sysActivityResponses;
    }

    @Override
    public void off(DealRequest dealRequest) {
        String id = dealRequest.getId();
        if (ObjectUtils.isEmpty(id)) {
            throw new RuntimeException("id不能为空");
        }
        Activity activity = activityMapper.selectById(id);
        if (ObjectUtils.isEmpty(activity)) {
            throw new RuntimeException("记录不存在");
        }
        activity.setStatus(SettingStatusEnum.OFF.getStatus());
        activity.setUpdateTime(new Date());
        activityMapper.updateById(activity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(DealRequest dealRequest) {
        String id = dealRequest.getId();
        if (ObjectUtils.isEmpty(id)) {
            throw new RuntimeException("id不能为空");
        }
        Activity activity = activityMapper.selectById(id);
        if (!activity.getStatus().equals(SettingStatusEnum.NOT_STARTED.getStatus())) {
            throw new RuntimeException("仅允许删除未开始的活动");
        }
        if (ObjectUtils.isEmpty(activity)) {
            throw new RuntimeException("记录不存在");
        }
        activity.setDeleted(true);
        activity.setUpdateTime(new Date());
        activityMapper.updateById(activity);
        activityRewardRulesService.update(new LambdaUpdateWrapper<ActivityRewardRules>().set(ActivityRewardRules::getDeleted, true).eq(ActivityRewardRules::getActivityId, activity.getId()));
    }

    @Override
    public BigDecimal getByType(Integer type) {
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        Activity activity = activityMapper.selectOne(activityQueryWrapper);
//        if (!ObjectUtils.isEmpty(activity)) {
//            return activity.getRewardAmount();
//        }
        return null;
    }

    @Override
    public Activity getSettings(Integer type) {
        Date date = new Date();
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        activityQueryWrapper.eq("reward_type", type);
        activityQueryWrapper.eq("deleted", false);
        activityQueryWrapper.le("start_activity_time", date);
        activityQueryWrapper.ge("end_activity_time", date);
        activityQueryWrapper.ne("status", SettingStatusEnum.OFF.getStatus());
        activityQueryWrapper.orderByDesc("create_time");
        activityQueryWrapper.last("limit 1");
        Activity activity = activityMapper.selectOne(activityQueryWrapper);
        return activity;
    }

    @Override
    public Activity getSettings(String activityId) {
        Date date = new Date();
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        activityQueryWrapper.eq("id", activityId);
        activityQueryWrapper.eq("deleted", false);
        activityQueryWrapper.le("start_activity_time", date);
        activityQueryWrapper.ge("end_activity_time", date);
        activityQueryWrapper.ne("status", SettingStatusEnum.OFF.getStatus());
        Activity activity = activityMapper.selectOne(activityQueryWrapper);
        return activity;
    }

    @Override
    public Boolean checkEffectiveness(String activityId) {
        Date date = new Date();
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        activityQueryWrapper.eq("id", activityId);
        activityQueryWrapper.eq("deleted", false);
        activityQueryWrapper.le("start_activity_time", date);
        activityQueryWrapper.ge("end_activity_time", date);
        activityQueryWrapper.ne("status", SettingStatusEnum.OFF.getStatus());
        Activity activity = activityMapper.selectOne(activityQueryWrapper);
        return !ObjectUtils.isEmpty(activity);
    }

    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void autoLoadAndUnload() {
        log.info("--------开始扫描上下架推广活动--------时间为------{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        List<Activity> activityList = activityMapper.selectList(new QueryWrapper<Activity>().and(wrapper -> wrapper.eq("deleted", DEL).eq("status", SettingStatusEnum.NOT_STARTED.getStatus())).or(wrapper -> wrapper.eq("status", SettingStatusEnum.ON_DISPLAY.getStatus())));
        ArrayList<String> activityNoStartIds = new ArrayList<>();
        ArrayList<String> activityLoadingIds = new ArrayList<>();
        for (Activity activity : activityList) {
            if (SettingStatusEnum.NOT_STARTED.getStatus().equals(activity.getStatus()) && System.currentTimeMillis() >= activity.getStartActivityTime().getTime()) {
                activityNoStartIds.add(activity.getId());
            }
            if (SettingStatusEnum.ON_DISPLAY.getStatus().equals(activity.getStatus()) && System.currentTimeMillis() >= activity.getEndActivityTime().getTime()) {
                activityLoadingIds.add(activity.getId());
            }
        }
        Activity activityStart = new Activity();
        activityStart.setStatus(SettingStatusEnum.ON_DISPLAY.getStatus());
        if (!CollectionUtils.isEmpty(activityNoStartIds)) {
            activityMapper.update(activityStart, new UpdateWrapper<Activity>().in("id", activityNoStartIds));
        }

        Activity activityEnd = new Activity();
        activityEnd.setStatus(SettingStatusEnum.ENDED.getStatus());
        if (!CollectionUtils.isEmpty(activityLoadingIds)) {
            activityMapper.update(activityEnd, new UpdateWrapper<Activity>().in("id", activityLoadingIds));
        }
    }

    @Override
    public ActivityRewardRules getSettingsByProductType(Byte productType, String activityId) {
        QueryWrapper<ActivityRewardRules> activityRewardRulesQueryWrapper = new QueryWrapper<>();
        activityRewardRulesQueryWrapper.lambda().eq(ActivityRewardRules::getProductType, productType).eq(ActivityRewardRules::getActivityId, activityId).eq(ActivityRewardRules::getDeleted, false);
        return activityRewardRulesMapper.selectOne(activityRewardRulesQueryWrapper);
    }

}
